# -*- coding:utf-8 -*-
import datetime
import md5

from google.appengine.api import users
from google.appengine.api import memcache
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.utils import simplejson

from django.conf import settings

def login_required( func ):
    """登录验证"""
    def wrap(request,*args,**kwargs):
        if not users.get_current_user():
            # 通过Google 用户API 检查用户
            return HttpResponseRedirect(
                    users.create_login_url(request.GET.get('continue'))
            )
        
        return func(request,*args,**kwargs)
    return wrap
##############################
#
#    未使用
#def master_required( view ):
#    """需要管理员身份"""
#    def wrap(request,*args,**kwargs):
#        if not request.user == request.master:
#            return HttpResponseForbidden()
#        else:
#            return view(request,*args,**kwargs)
#    return wrap
#
##############################

def admin_required( func ):
    """需要管理员权限"""
    def wrap(request,*args,**kwargs):
        if not users.is_current_user_admin():
            if request.method == 'GET':
                return  HttpResponseRedirect(users.create_login_url(request.path))
            else:
                return HttpResponse('Permission Denied')
        return func(request,*args,**kwargs)
    return wrap

def expose( type,html = '',error='error.html',check_ajax=True,redirect=None):
    def wrap(func):
        def render(request,**kwargs):
            if kwargs:
                context = func( request ,kwargs )
            else:
                context = func( request )

            if type == 'json':
                return HttpResponse(simplejson.dumps(context))
            if check_ajax and request.is_ajax():
                return HttpResponse(simplejson.dumps(context))
            
            if not redirect:
                redirect = context.get('redirect')
            if redirect:
                return HttpRedirect(redirect)

        return render
    return wrap

def _cntime():
    """根据GAE的UTC时间计算中国时区的时间"""
    return datetime.datetime.utcnow() + datetime.timedelta(hours=+8)

def cache_page(seconds,vary_user=False):
    """
    通过memcache 对view的输出结果进行缓存 
    @param vary_user: 是否对不同的用户进行不同的缓存
    """
    def deco(view):
        def wrap(request, *args):
            if request.method == 'GET':
                key = view.__name__ + '_' + '_'.join([ str(argu.encode('utf-8')) for argu in args])
                # 将 HTTP_ACCEPT 的值加入 KEY 中
                # 主要区别 WAP浏览器 和 PC浏览器
                key += md5.md5(request.META.get('HTTP_ACCEPT')).hexdigest()
                if vary_user:
                    user = users.get_current_user()
                    if user:
                        key = "%s_%s" %( user.user_id() , key )
        
                resp = memcache.get(key)

                if resp:
                    return resp
                else:
                    resp = view(request , *args )
                    memcache.set( key , resp ,seconds)
                    return resp

            return view(request,*args)
        return wrap
    return deco

def clear_cache(key='',key_start=''):
    """
    Clear cache whose key is key or starts with key_start
    @note: Only 'POST' request will clear the cache
    """
    def deco(view):
        def wrap( request , * args , **kwargs ):
            if request.method == 'POST':
                resp = view( request , *args ,**kwargs)
                if not key:
                    memcache.flush_all()
                return resp

            return view( request ,*args,**kwargs)
        return wrap

    return deco

def blank(*args,**kwargs):
    """在开发状态(DEBUG=True)时，取消缓存"""
    def deco(view):
        def wrap(request,*args,**kwargs):
            return view(request,*args,**kwargs)
        return wrap
    return deco

if settings.DEBUG:
    cache_page = blank
    clear_cache = blank

